from fastapi import APIRouter, Cookie, Header, Depends, Response


router = APIRouter()


def level_1():
    print("level_1")
    return 10


def level_2a(t2a: int = Depends(level_1)):
    print("level_2a")
    return 20 + t2a


def level_2b(t2b: int = Depends(level_1)):
    print("level_2b")
    return 40 + t2b


def level_3(l2b: int = Depends(level_2b), l2a: int = Depends(level_2a)):
    # 这里 重复使用了Depends(level_1)，会缓存结果，不会重复打印level_1
    print("level_3")
    return l2a + l2b


# 函数作依赖
def query_depends(user: str, token: str):
    # 获取Cookie
    pan_token = Cookie(default=None, alias="pan_token")
    data = {"user": user, "token": token, "pan_token": pan_token}
    return data


# 类作依赖
class User:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age


@router.get("/depends_show")
async def depends_show(
    response: Response,
    total: int = Depends(level_3),
    common: str = Depends(query_depends),
    user: User = Depends(User),
    pan_token: str = Header(default=None),
):
    print("cookie", pan_token)
    response.set_cookie(key="pan_token", value=pan_token)

    data = {"total": total, "common": common, "user": user}
    return data
